package com.tridion.utilities.verifier.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ChecksumUtil {
    
    // private constructor to prevent instances
    private ChecksumUtil(){}
    
    private static final String ALGORITHM = "SHA1";
    
    /**
     * Generates the SHA1 checksum for a file.
     */
    public static String generateChecksum(final File file) {
        try {
            final MessageDigest md = MessageDigest.getInstance(ALGORITHM);
            final FileInputStream fis = new FileInputStream(file);
            byte[] dataBytes = new byte[1024];

            int nread = 0;

            while ((nread = fis.read(dataBytes)) != -1) {
                md.update(dataBytes, 0, nread);
            }
            
            fis.close();

            byte[] mdbytes = md.digest();

            // convert the byte to hex format
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < mdbytes.length; i++) {
                sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
            }

            return sb.toString();
        } catch (IOException ioe) {
            // TODO Auto-generated catch block
            ioe.printStackTrace();
            
            return "error";
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            
            return "error";
        }
    }
    
    // this is an internal test method
    public static void main(String[] args) {
        if (args != null && args.length > 0) {
            final String folderLocation = args[0];
            final File folder = new File(folderLocation);
            if (folder.exists() && folder.isDirectory()) {
                for (File jar : folder.listFiles()) {
                    final String jarVersion = JarUtil.getJarVersion(jar);
                    final String checksum = generateChecksum(jar);
                    System.out.println("<jar name=\"" + jar.getName() + "\" releaseVersion=\"2011 SP1\" version=\"" 
                            + jarVersion + "\" checksum=\"" + checksum + "\"/>");
                }
            } else {
                System.out.println("Given folder is not valid location");
            }
        } else {
            System.out.println("Usage: java -jar <jar_file>.jar <folderLocation>");
        }
    }
}
